<?php
class Friend extends AppModel {

	var $name = 'Friend';

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'UserTo' => array(
			'className' => 'User',
			'foreignKey' => 'userfriend',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
	);
	//バリデート
	var $validate = array(
		'status' => array(
			'rule' => array('isInArray', array('active', 'disable', 'notActive')),
		),
		'user_id' => array(
			'rule' => array('isPlusNumber'),
		),
		'userfriend' => array(
			'rule' => array('isPlusNumber'),
		),
		'ip' => array(
			'rule' =>array('ip'),
		),
		'message' => array(
			'length' => array(
				'rule' =>array('maxLength', 400),
				'message' => 'メッセージは400文字までです',
			),
			'kaigyo' => array(
				'rule' => array('kaigyoLessThanN', 4),
				'message' => 'メッセージは5行までです',
			),
		),
	);
	function isUser($viewUserID, $postedUserID)
	{
		return ($viewUserID === $postedUserID);
	}
	
	function isUserFriend($viewUserID, $postedUserID)
	{
		$cond = array(
			'userfriend' => '= '.$viewUserID,
			'user_id' => '= '.$postedUserID,
			'status' => '= active',
		);
		return $this->hasAny($cond);
	}
	
	function isUserFriendFriend($viewUserID, $postedUserID)
	{
		$friendsfriends = $this->query(
			"SELECT	FriendFriend.userfriend
			FROM friends AS Friend
			INNER JOIN friends AS FriendFriend ON (Friend.userfriend = FriendFriend.user_id)
			WHERE Friend.user_id = '{$postedUserID}' AND Friend.status = 'active' AND FriendFriend.status = 'active' AND FriendFriend.userfriend = '{$viewUserID}'");
		
		/*
		array[0][FriendFriend][userfriend]が返ってくる 該当しなければ空っぽ
		*/
		return (empty($friendsfriends)) ? false : true;
	}
	
	function register($userID, $userfriend, $mode = null)
	{
		$data = array();
		if($mode === 'activated'){$data['status'] = 'active';}
		else{$data['status'] = 'notActive';}
		$data['user_id'] = $userID;
		$data['userfriend'] = $userfriend;
		$data['ip'] = $this->RHgetClientIP();
		
		return $this->save(array($this->name => $data));
	}
	
	function checkActivate($token)
	{
		//トークンチェック
		$salt = Configure::read('salt.friend');
		if(!$this->data || $token !== md5($salt.strtotime($this->data[$this->name]['modified']))){
			$this->invalidate('friend', 'そんなオファー無いです or このオファーは登録済みです');
			return false;
		}
		
		//重複チェック
		$cond = array();
		$cond['user_id'] = $this->data[$this->name]['user_id'];
		$cond['userfriend'] = $this->data[$this->name]['userfriend'];
		$cond['status'] = 'active';
		$cond['id'] = '!= '.$this->data[$this->name]['id'];
		
		if($this->findCount($cond, -1) !== 0){
			$this->invalidate('already', 'マイフレンド登録済みです');
			return false;
		}
		return true;
	}

}
?>